import { pageType, userType } from "@/types"
import { ReloadOutlined } from "@ant-design/icons"
import { http } from "@/utils/http"
import { Button, Descriptions, Form, Input, message, Modal, Popconfirm, Select, Switch, Table } from "antd"
import { ColumnsType } from "antd/lib/table"
import React, { useCallback, useEffect, useState } from "react"
import styles from "./index.module.scss"
import { connect, ConnectedProps } from "react-redux"
// import store from "@/store"

type Props = ConnectedProps<typeof connector>

const UserPanel: React.FC<Props> = (props) => {
  const { userInfo } = props

  const [userList, setUserList] = useState<userType[]>([])
  const [pageState, setPageState] = useState<pageType>({ pages: 0, total: 0, paramsData: { currentPage: 1, pageSize: 100 } })
  const [currentUser, setCurrentUser] = useState<userType>()
  const [addModalVisible, setAddModalVisible] = useState(false)
  const [detailModalVisible, setDetailVisible] = useState(false)
  const [regionList, setRegionList] = useState<string[]>([])
  const [form] = Form.useForm()

  const getRoleName = useCallback((role: number = 4) => {
    return role === 1 ? "超级管理员" : role === 2 ? "省管理员" : role === 3 ? "市管理员" : "县管理员"
  }, [])

  const roleNameMap = new Map([
    ["超级管理员", 1],
    ["省管理员", 2],
    ["市管理员", 3],
    ["县管理员", 4],
  ])

  const columns: ColumnsType<userType> = [
    {
      title: "用户名",
      dataIndex: "username",
      key: "username",
    },
    {
      title: "角色",
      dataIndex: "role",
      key: "role",
      filters: [
        { text: "超级管理员", value: 1 },
        { text: "省管理员", value: 2 },
        { text: "市管理员", value: 3 },
        { text: "县管理员", value: 4 },
      ],
      onFilter: (value, user) => user.role === value,
      render: (role: number) => {
        return <span style={role === 1 ? { color: "#f56a00" } : {}}>{getRoleName(role)}</span>
      },
    },
    {
      title: "区域",
      dataIndex: "region",
      key: "region",
    },
    {
      title: "注册时间",
      dataIndex: "joinDate",
      key: "joinDate",
    },
    {
      title: "状态",
      dataIndex: "roleState",
      key: "roleState",
      filters: [
        { text: "启用", value: true },
        { text: "禁用", value: false },
      ],
      onFilter: (value, user) => user.roleState === value,
      render: (roleState: boolean, user: userType) => {
        return (
          <Switch
            checked={roleState}
            disabled={user.role === 1}
            checkedChildren="启用"
            unCheckedChildren="禁用"
            onChange={(checked) => changeRoleState(user.uid, checked)}
          />
        )
      },
    },
    {
      title: "操作",
      align: "center",
      render: (user: userType) => {
        return (
          <>
            <Button type="link" size="small" onClick={() => openDetailModal(user)}>
              详细
            </Button>
            <Popconfirm
              title="确定要删除该管理员吗?"
              placement="topRight"
              cancelText="取消"
              okText="确定"
              onConfirm={() => deleteAdministrator(user.uid)}
              disabled={user.role === 1 ? true : false}
            >
              <Button type="link" danger size="small" disabled={user.role === 1 ? true : false}>
                删除
              </Button>
            </Popconfirm>
          </>
        )
      },
    },
  ]

  useEffect(() => {
    // 获取用户列表
    getUserList()
  }, [])

  useEffect(() => {
    // 获取地区列表
    http
      .get(`/get/region?regionName=${userInfo.region}`)
      .then(({ data: res }) => setRegionList(res.data))
      .catch((err) => {})
  }, [userInfo.region])

  /**
   * 获取用户列表
   */
  const getUserList = async () => {
    try {
      const { data: res } = await http.get(`/get/user?currentPage=${1}&pageSize=${100}`)
      setPageState({
        pages: res.data.pages,
        total: res.data.total,
        paramsData: { currentPage: 2, pageSize: 100 },
      })
      setUserList(res.data.list)
    } catch {}
  }

  /**
   * 添加管理员
   */
  const addAdministrator = async () => {
    const formData = await form.validateFields()
    const res = await http.post("/create/user", { ...formData, role: roleNameMap.get(formData.roleName) })
    if (res.status !== 200) return message.error("添加失败")
    getUserList()
    message.success("创建成功")
    setAddModalVisible(false)
    form.resetFields()
  }

  /**
   * 删除管理员
   * @param uid 用户id
   */
  const deleteAdministrator = async (uid: string | number) => {
    const res = await http.post(`/modify/user/state?otherId=${uid}&way=delete`)
    if (res.status !== 200) return message.error("删除失败")
    getUserList()
    message.success("已删除该管理员")
  }

  /**
   * 修改用户的状态
   * @param uid 用户id
   * @param checked 待修改成的状态
   */
  const changeRoleState = (uid: string | number, checked: boolean) => {
    setUserList(userList.map((user) => (user.uid === uid ? { ...user, roleState: checked } : user)))
    http
      .post(`/modify/user/state?otherId=${uid}&way=modify`)
      .then((res) => {
        message.success("操作成功")
      })
      .catch((err) => {
        message.error("操作失败")
      })
  }

  const openDetailModal = (user: userType) => {
    setCurrentUser(user)
    setDetailVisible(true)
  }

  /**
   * 加载更多
   * @returns void
   */
  const loadMore = async () => {
    if (userList.length === pageState.total) return message.warning("没有更多了")
    const { currentPage, pageSize } = pageState.paramsData
    const { data: res } = await http.get(`/get/user?currentPage=${currentPage}&pageSize=${pageSize}`)
    setUserList([...userList, ...res.data.list])
    setPageState({
      pages: res.data.pages,
      total: res.data.total,
      paramsData: { currentPage: currentPage + 1, pageSize: 100 },
    })
  }

  return (
    <>
      <div className={styles["operation-panel"]}>
        <Button type="primary" onClick={() => setAddModalVisible(true)}>
          新建管理员
        </Button>

        <Button type="primary" icon={<ReloadOutlined />} onClick={loadMore}>
          加载更多
        </Button>
      </div>

      <Table
        rowKey={(user) => user.uid}
        rowSelection={{ checkStrictly: true }}
        dataSource={userList}
        columns={columns}
        pagination={{ pageSize: 7 }}
      />

      <Modal title="新建管理员" visible={addModalVisible} onOk={addAdministrator} onCancel={() => setAddModalVisible(false)}>
        <Form autoComplete="off" initialValues={{ roleName: getRoleName(userInfo.role + 1), region: regionList[0] }} form={form}>
          <Form.Item
            labelAlign="left"
            label="用户名"
            name="username"
            rules={[
              { required: true, message: "请输入用户名!" },
              { min: 2, max: 9, message: "用户名长度不符合" },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="密码"
            name="password"
            rules={[
              { required: true, message: "请输入密码!" },
              { min: 6, max: 12, message: "密码长度不符合" },
            ]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item label="角色" name="roleName" rules={[{ required: true, message: "Please input your role!" }]}>
            <Input disabled />
          </Form.Item>
          <Form.Item label="管辖区域" name="region" rules={[{ required: true, message: "Select input your region!" }]}>
            <Select>
              {regionList.map((region) => {
                return (
                  <Select.Option value={region} key={region}>
                    {region}
                  </Select.Option>
                )
              })}
            </Select>
          </Form.Item>
        </Form>
      </Modal>

      <Modal title="管理员信息" visible={detailModalVisible} footer={null} onCancel={() => setDetailVisible(false)} width={750}>
        {currentUser !== undefined && (
          <Descriptions bordered>
            <Descriptions.Item label="uid">{currentUser.uid}</Descriptions.Item>
            <Descriptions.Item label="用户名">{currentUser.username}</Descriptions.Item>
            <Descriptions.Item label="密码">{currentUser.password}</Descriptions.Item>
            <Descriptions.Item label="角色">{getRoleName(currentUser.role)}</Descriptions.Item>
            <Descriptions.Item label="区域">{currentUser.region}</Descriptions.Item>
            <Descriptions.Item label="状态">{currentUser.roleState ? "启用" : "禁用"}</Descriptions.Item>
            <Descriptions.Item label="注册时间">{currentUser.joinDate}</Descriptions.Item>
          </Descriptions>
        )}
      </Modal>
    </>
  )
}

const connector = connect((state: userType) => ({ userInfo: state }))

export default connector(UserPanel)
